/**
 * 修复数据库中空的 employee_id
 * 将空字符串的 employee_id 设置为 NULL，避免唯一索引冲突
 */

require('dotenv').config();
const { pool } = require('../config/db');

async function fixEmptyEmployeeId() {
  try {
    console.log('开始修复空的 employee_id...');
    
    // 将空字符串的 employee_id 设置为 NULL
    const [result] = await pool.execute(
      `UPDATE system_users 
       SET employee_id = NULL 
       WHERE employee_id = '' OR employee_id IS NULL OR TRIM(employee_id) = ''`
    );
    
    console.log(`✓ 已修复 ${result.affectedRows} 条记录`);
    
    // 同样处理 email 和 phone
    const [emailResult] = await pool.execute(
      `UPDATE system_users 
       SET email = NULL 
       WHERE email = '' OR TRIM(email) = ''`
    );
    console.log(`✓ 已修复 ${emailResult.affectedRows} 条空邮箱记录`);
    
    const [phoneResult] = await pool.execute(
      `UPDATE system_users 
       SET phone = NULL 
       WHERE phone = '' OR TRIM(phone) = ''`
    );
    console.log(`✓ 已修复 ${phoneResult.affectedRows} 条空手机记录`);
    
    console.log('\n修复完成！现在可以正常创建用户了。');
    
  } catch (error) {
    console.error('修复失败:', error.message);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

// 运行修复
fixEmptyEmployeeId();

